/**
 * 项目管理服务
 * 负责项目的创建、打开、验证等操作
 */

import { formatTime, generateId } from '@/utils/common'

// 项目类型定义
export interface ProjectInfo {
  id: string
  name: string
  path: string
  createTime: string
  lastOpenTime?: string
  description?: string
  files: Record<string, string>
}

// 项目文件类型
export interface ProjectFile {
  name: string
  path: string
  type: string
  size?: number
  modified?: string
}

class ProjectService {
  private currentProject: ProjectInfo | null = null
  private readonly PROJECT_STORAGE_KEY = 'simion-projects'
  private readonly CURRENT_PROJECT_KEY = 'simion-current-project'

  /**
   * 获取所有项目列表
   */
  async getProjects(): Promise<ProjectInfo[]> {
    try {
      const projects = localStorage.getItem(this.PROJECT_STORAGE_KEY)
      if (projects) {
        return JSON.parse(projects)
      }
      return []
    } catch (error) {
      console.error('获取项目列表失败:', error)
      return []
    }
  }

  /**
   * 保存项目列表
   */
  private async saveProjects(projects: ProjectInfo[]): Promise<void> {
    try {
      localStorage.setItem(this.PROJECT_STORAGE_KEY, JSON.stringify(projects))
    } catch (error) {
      console.error('保存项目列表失败:', error)
      throw new Error('保存项目失败')
    }
  }

  /**
   * 创建新项目
   */
  async createProject(projectData: {
    name: string
    path: string
    description?: string
  }): Promise<ProjectInfo> {
    try {
      // 验证项目名称
      if (!projectData.name || projectData.name.trim() === '') {
        throw new Error('项目名称不能为空')
      }

      // 验证项目路径
      if (!projectData.path || projectData.path.trim() === '') {
        throw new Error('项目路径不能为空')
      }

      // 构建完整的项目路径
      const fullProjectPath = `${projectData.path}/${projectData.name}`.replace(/\/+/g, '/')
      
      // 检查项目是否已存在
      const existingProjects = await this.getProjects()
      const existingProject = existingProjects.find(
        p => p.path === fullProjectPath || (p.name === projectData.name && p.path === projectData.path)
      )
      if (existingProject) {
        throw new Error('项目已存在')
      }

      // 创建项目信息
      const newProject: ProjectInfo = {
        id: generateId(),
        name: projectData.name.trim(),
        path: fullProjectPath,
        createTime: formatTime(new Date()),
        description: projectData.description?.trim() || '',
        files: {}
      }

      // 保存项目
      existingProjects.push(newProject)
      await this.saveProjects(existingProjects)

      return newProject
    } catch (error) {
      throw new Error(`创建项目失败: ${(error as Error).message}`)
    }
  }

  /**
   * 打开项目
   */
  async openProject(projectPath: string): Promise<ProjectInfo> {
    try {
      // 验证项目路径
      if (!projectPath || projectPath.trim() === '') {
        throw new Error('项目路径不能为空')
      }

      // 检查项目是否存在
      const projects = await this.getProjects()
      let project = projects.find(p => p.path === projectPath)

      if (!project) {
        // 如果项目不在列表中，尝试从路径创建项目信息
        const scannedProject = await this.scanProject(projectPath)
        if (scannedProject) {
          project = scannedProject
          projects.push(project)
          await this.saveProjects(projects)
        }
      }

      if (!project) {
        throw new Error('项目不存在或无效')
      }

      // 更新最后打开时间
      project.lastOpenTime = formatTime(new Date())
      await this.saveProjects(projects)

      // 设置为当前项目
      this.currentProject = project
      localStorage.setItem(this.CURRENT_PROJECT_KEY, JSON.stringify(project))

      return project || undefined
    } catch (error) {
      throw new Error(`打开项目失败: ${(error as Error).message}`)
    }
  }

  /**
   * 扫描项目目录
   */
  async scanProject(projectPath: string): Promise<ProjectInfo | null> {
    try {
      // 调用Electron API来扫描文件系统
      if ((window as any).electronAPI) {
        const result = await (window as any).electronAPI.scanProject(projectPath)
        if (result.isValid) {
          return {
            id: generateId(),
            name: result.name,
            path: result.path,
            createTime: formatTime(new Date()),
            files: {}
          }
        } else {
          throw new Error(result.error || '项目路径无效')
        }
      } else {
        // 回退到基本项目信息
        const projectName = projectPath.split(/[/\\]/).pop() || '未知项目'
        return {
          id: generateId(),
          name: projectName,
          path: projectPath,
          createTime: formatTime(new Date()),
          files: {}
        }
      }
    } catch (error) {
      console.error('扫描项目失败:', error)
      return null
    }
  }

  /**
   * 验证项目文件
   */
  async validateProject(projectPath: string): Promise<{
    valid: boolean
    files: ProjectFile[]
    errors: string[]
  }> {
    const errors: string[] = []
    const files: ProjectFile[] = []

    try {
      // 调用Electron API来检查文件系统
      if ((window as any).electronAPI) {
        const result = await (window as any).electronAPI.validateProject(projectPath)
        return {
          valid: result.valid,
          files: result.files.map((file: any) => ({
            name: file.name,
            path: file.path,
            type: file.type,
            size: file.size,
            modified: formatTime(new Date())
          })),
          errors: result.errors
        }
      } else {
        // 回退到模拟数据（开发环境）
        // 模拟扫描文件夹中的所有文件
        const mockFiles = [
          { name: 'example.txt', type: 'txt', size: 1024 },
          { name: 'data.csv', type: 'csv', size: 2048 },
          { name: 'config.json', type: 'json', size: 512 }
        ]

        for (const file of mockFiles) {
          files.push({
            name: file.name,
            path: `${projectPath}/${file.name}`,
            type: file.type as any,
            size: file.size,
            modified: formatTime(new Date())
          })
        }

        return {
          valid: true,
          files,
          errors: []
        }
      }
    } catch (error) {
      errors.push(`验证项目失败: ${(error as Error).message}`)
      return {
        valid: false,
        files,
        errors
      }
    }
  }

  /**
   * 获取当前项目
   */
  getCurrentProject(): ProjectInfo | null {
    if (this.currentProject) {
      return this.currentProject
    }

    try {
      const currentProjectData = localStorage.getItem(this.CURRENT_PROJECT_KEY)
      if (currentProjectData) {
        this.currentProject = JSON.parse(currentProjectData)
        return this.currentProject
      }
    } catch (error) {
      console.error('获取当前项目失败:', error)
      // 如果解析失败，清除无效数据
      this.clearInvalidProject()
    }

    return null
  }

  /**
   * 清除无效的当前项目数据
   */
  private clearInvalidProject(): void {
    this.currentProject = null
    localStorage.removeItem(this.CURRENT_PROJECT_KEY)
  }

  /**
   * 关闭当前项目
   */
  closeCurrentProject(): void {
    this.currentProject = null
    localStorage.removeItem(this.CURRENT_PROJECT_KEY)
  }

  /**
   * 删除项目
   */
  async deleteProject(projectId: string): Promise<void> {
    try {
      const projects = await this.getProjects()
      const filteredProjects = projects.filter(p => p.id !== projectId)
      
      if (filteredProjects.length === projects.length) {
        throw new Error('项目不存在')
      }

      await this.saveProjects(filteredProjects)

      // 如果删除的是当前项目，关闭当前项目
      if (this.currentProject?.id === projectId) {
        this.closeCurrentProject()
      }
    } catch (error) {
      throw new Error(`删除项目失败: ${(error as Error).message}`)
    }
  }

  /**
   * 获取最近项目
   */
  async getRecentProjects(limit: number = 5): Promise<ProjectInfo[]> {
    const projects = await this.getProjects()
    return projects
      .filter(p => p.lastOpenTime)
      .sort((a, b) => new Date(b.lastOpenTime!).getTime() - new Date(a.lastOpenTime!).getTime())
      .slice(0, limit)
  }

  /**
   * 检查项目是否有效
   */
  async isProjectValid(projectPath: string): Promise<boolean> {
    try {
      const validation = await this.validateProject(projectPath)
      return validation.valid
    } catch {
      return false
    }
  }
}

// 导出单例实例
export const projectService = new ProjectService()
export default projectService
